﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AppToolKit.Core.AttributeDiscovery;
using AppToolKit.Core.Context;
using System.Reflection;

namespace App.Service
{
    public abstract class AppEnvBase : IAppEnv
    {
        private string appId_;
        protected ModuleStorage modules_ = new ModuleStorage();

        public string AppId
        {
            get { return appId_; }
            set { appId_ = value; }
        }


        public AssemblyDetector Detector { private get; set; }
        public IContextManager ContextMgr { protected get; set; }

        protected void AddModule(string assembly)
        {
            if (!modules_.ContainsKey(assembly))
            {
                modules_.Add(assembly, null);
                return;
            }
            throw new Exception();

        }

        /// <summary>
        /// 用来初始化
        /// </summary>

        protected virtual void DoProcessModule()
        {
            EnsureLoad();
            Detector.Init();
            OnProcess();
        }

        protected abstract void OnProcess();

        protected void EnsureLoad()
        {
            foreach (string assembly in modules_.Keys)
            {
                bool found = false;
                foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies())
                {
                    if (assembly == a.GetName().Name)
                    {
                        found = true;
                        break;
                    }
                }
                if (!found)
                    Assembly.Load(assembly);

            }
        }
    }
}